<?
	//gestione banner
	class bannerClient  {
		var $idclient;
		var $nome;
		var $contatto;
		var $mail;
		var $telefono;
		var $lang;
		
		function bannerClient($idclient="")  {
		  global $conn;
		  if($idclient != "")  {
		    $qry = "SELECT * FROM banner_client WHERE idclient='$idclient';";
			$rs = $conn->Execute($qry);
			if($rs)  {
			  $this->idclient = $rs->Fields("idclient");
			  $this->nome = $rs->Fields("nome");
			  $this->contatto = $rs->Fields("contatto");
			  $this->mail = $rs->Fields("mail");
			  $this->telefono = $rs->Fields("telefono");
			  $this->lang = $rs->Fields("lang");
			  $rs->Close();
			}  
		  } else {
			  $this->idclient = NULL;
			  $this->nome = NULL;
			  $this->contatto = NULL;
			  $this->mail = NULL;
			  $this->telefono = NULL;
			  $this->lang = NULL;		    
		  }
		}
		
		function save($nome,$contatto,$mail,$telefono)  {
		  global $conn,$lang;
			//controllo la mail
		   if($mail != "")  {
			if (!eregi("^[a-z0-9][_\.a-z0-9-]+@([a-z0-9][0-9a-z-]+\.)+([a-z]{2,4})", $mail))  {
			      $error = "Indirizzo e-mail non valido.";
			  	  return $error;
			 }
			}
		  $qry = "INSERT INTO banner_client VALUES(NULL,'$nome','$contatto','$mail','$telefono','$lang');";
		  //die($qry);
		  $rs = $conn->Execute($qry);
			if($rs)  {
			  $error = 0;
			  $rs->Close();
	        } else {
	             $error = "Inserimento errato.<br>Ripetere l'operazione.";
			}
			return $error;			  
		}
		
		function update($nome,$contatto,$mail,$telefono)	{
		  global $conn;
		  $qry = "UPDATE banner_client SET nome='$nome',contatto='$contatto',mail='$mail',telefono='$telefono' WHERE idclient='$this->idclient';";
		  $rs = $conn->Execute($qry);
			if($rs)  {
			  $error = "Aggiornamento avvenuto con successo!";
			  $rs->Close();
	        } else {
	             $error = "Inserimento errato.<br>Ripetere l'operazione.";
			}
			return $error;			  
		}  

		function delete()  {
		  global $conn;
		  $qry = "DELETE FROM banner_client WHERE idclient='$this->idclient';";
		  $rs = $conn->Execute($qry);
			if($rs)  {
			  $error = 0;
			  $rs->Close();
	        } else {
	             $error = "Inserimento errato.<br>Ripetere l'operazione.";
			}
			return $error;			  
		}

	  function search($search)  {
	    global $conn,$admin;
	    if(strlen($search) <= 2)  {
		  $error = printError("Hai inserito una parola non significativa. Riprova con un'altra.");
		  return $error;
		}
		$qry = "SELECT idclient FROM banner_client WHERE nome LIKE '%$search%' OR mail LIKE '%$search%' ORDER BY nome ASC";
		$rs = $conn->Execute($qry);
		if($rs) {
			if($rs->RecordCount() > 0)  {
			  	 $i = $min + 1;
                 $content = "<table class=\"content\" width=\"100%\" align=\"center\" cellpadding=\"3\" cellspacing=\"0\" border=1>\n"
                 ."<tr>
					<td colspan=6>Sono stati trovati <b>".$rs->RecordCount()."</b> clienti.</td>
				 	</tr>
				 <tr>
				   <td class=\"tbtit\" align=\"center\" width=\"10%\"><b>Numero</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"20%\"><b>Nome</b></td>
				   <td class=\"tbtit\" align=\"\" width=\"20%\"><b>Contatto</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"20%\"><b>E-mail</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"10%\"><b>Telefono</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"20%\"><b>Azioni</b></td>
				 </tr>";
               while (!$rs->EOF)  {
				 $client = new bannerClient($rs->Fields("idclient"));
				 $idclient = $client->idclient;
				 $azioni = "<a href=\"banner.php?op=mod_client&idclient=$idclient\"><img src=\"imgs/ico_edit.gif\" alt=\"modifica\" width=16 height=16 title=\"modifica\" border=\"0\"></a>&nbsp;&nbsp;
                  <a href=\"banner.php?op=delete_client&idclient=$idclient\" onclick='return confirm(\"Sei sicuro di voler eliminare questo Cliente? \")'><img src=\"imgs/ico_delete.gif\" width=16 height=16 alt=\"cancella\" title=\"cancella\" border=\"0\"></a>";                 
				  $content .= "<tr>
				  				<td class=\"tbtit\" align=\"center\" width=\"10%\"><b>$i</b></td>
				 				<td class=tdelenco align=center>&nbsp;".$client->nome."</td>
								<td class=tdelenco>&nbsp;".$client->contatto."</td>
								<td class=tdelenco align=center>&nbsp;".$client->mail."</td>
								<td class=tdelenco align=center>&nbsp;".$client->telefono."</td>
								<td align=\"center\" valign=\"middle\" class=tdelenco>
								 $azioni";
                 $content .= "</td>
				 </tr>\n";
				 $rs->MoveNext();
				 $i++;
               }
			     $content .= "</table>";  
				 $rs->Close();
			} else {
			  $content = printError("La ricerca non ha prodotto nessun risultato.");		  
			}
		  $rs->Close();	
		} else {
			  $content = printError("La ricerca non ha prodotto nessun risultato.");		  
			}	
		return $content; 
	  }
}

	class banner  {
		var $fields;
		
		function banner($idbanner="")  {
		  global $conn;
		  if($idbanner!="")  {
		    $qry = "SELECT * FROM banner WHERE idbanner='$idbanner';";
			$rs = $conn->Execute($qry);
			if($rs->RecordCount() > 0) {
		  		$fields = $rs->FieldCount();
		  		for($i=0;$i<$fields;$i++)  {
		    		$field = $rs->FetchField($i);
		    		if($field->name == "startDate" || $field->name == "endDate") {
		    		  if($rs->Fields($field->name) != "0000-00-00")  {
					  list($a,$m,$g) = explode("-",$rs->Fields($field->name));
					  $value = "$g/$m/$a";
					} else 
					   $value = NULL;
					} else
					   $value = $rs->Fields($field->name);
					$this->fields[$field->name] = $value;
		  		}
		    }
		  } else {
		     $this->fields = NULL;  
		  } 		  
		}
		
		function save($post,$image)  {
	    	global $conn,$admin,$path_image_Banner, $path_image_Banner_ftp, $path_tmp, $max_size_image, $ftp_host,$ftp_username, $ftp_pwd, $_CONFIG, $lang;
		//controllo URL corretto
		if($post['clickurl'] != "" && $post['clickurl'] != "http://www.nomesito.it")  {
		  if(!@preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i',$post['clickurl']))  {
		    $error = "Il link al sito web non &egrave; corretto: controlla la sintassi.";
		    return $error;
		  }
		}				    	
		  if($post['clickurl'] == "http://www.nomesito.it")
		    $post["clickurl"] = "";
	    //controllo la presenza del banner
		 if($image["name"] != "")  {
	    	//imposto le dimensioni di controllo
	    	  $image["name"] = str_replace(" ","",$image["name"]);
		      banner::checkSize($post["posizione"]);
			  $swf = new Image($image["tmp_name"]);
			  $error = $swf->CheckSizeFormat($image,WIDTH,HEIGHT);
			  $my_swf = ",imageurl='$swf->name'";
		  } 
	    	$arrsave = array();
	    	$qry_fields = "";
	    	$arrfields = $conn->MetaColumnNames("banner");
###################### DEBUG #####################################################
	    	/*
			foreach($arrfields as $field => $value) {
			  $qry_fields .= "$value<br>";
			}
	    	foreach($post as $field => $value) {
			  $qry_fields .= "$field=$value<br>";
			}
			die($qry_fields);
			*/
##################################################################################
	    	foreach($post as $field => $value)  {
			  if(in_array($field,$arrfields)) {
			    $arrsave[$field] = $value;
			    if($field == "startDate" || $field == "endDate")  {
				  list($g,$m,$a) = explode("/",$value);
				  $value = "$a-$m-$g";
				}
				if($field == "idclient")
				  $qry_fields = "$field='$value'";
				else
				  $qry_fields .= ",$field='$value'";    
			  }
			}
		 $qry = "INSERT INTO banner SET $qry_fields,attivo='1',clicks='0',lang='$lang' $my_swf;";
		 //die($qry);
		 $rs = $conn->Execute($qry);
		 if($rs)  {
/////////////////////////copio swf o immagine ////////////////////////////////////
			         $id = $conn->Insert_ID();
			         $connect = ftp_connect($ftp_host);
					 $login = ftp_login($connect, $ftp_username, $ftp_pwd); 
			         if(ftp_mkdir($connect, $path_image_Banner_ftp.$id)) {
					   ftp_site($connect, "CHMOD 0777 ".$path_image_Banner_ftp.$id);
					   if(file_exists($path_tmp.$image["name"]) && $image["name"] != "") {
					     if(copy($path_tmp.$image["name"],$path_image_Banner.$id."/".$image["name"]))
					       unlink($path_tmp.$image["name"]);
					   }
					  ftp_site($connect, "CHMOD 0755 ".$path_image_Banner_ftp.$id);
					  ftp_quit($connect);    
					 }
         			$error = 0;
					$rs->Close();
	        } else {
	             $error = "Inserimento errato.<br>Ripetere l'operazione.";
			}
		return $error;			  		  
		}
	
		  function update($post,$image)  {
	    	global $conn,$admin,$path_image_Banner, $path_image_Banner_ftp, $path_tmp, $max_size_image, $ftp_host,$ftp_username, $ftp_pwd, $_CONFIG;	    	
	    	$arrsave = array();
	    	$qry_fields = "";
	    	$arrfields = $conn->MetaColumnNames("banner");
			//controllo URL corretto
			if($post['clickurl'] != "" && $post['clickurl'] != "http://www.nomesito.it")  {
			  if(!@preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i',$post['clickurl']))  {
			    $error = "Il link al sito web non &egrave; corretto: controlla la sintassi.";
			    return $error;
			  }  
			}				    	
	    	//controllo la presenza del banner
		 if($image["name"] != "")  {
	    	//imposto le dimensioni di controllo
	    	  $image["name"] = str_replace(" ","",$image["name"]);
		      banner::checkSize($this->fields["posizione"]);
			  $swf = new Image($image["tmp_name"]);
			  $error = $swf->CheckSizeFormat($image,WIDTH,HEIGHT);
			  $my_swf = ",imageurl='$swf->name'";
		  } 
###################### DEBUG #####################################################
	    	/*
			foreach($arrfields as $field => $value) {
			  $qry_fields .= "$value<br>";
			}
	    	foreach($post as $field => $value) {
			  $qry_fields .= "$field=$value<br>";
			}
			die($qry_fields);
			*/
##################################################################################
	    	foreach($post as $field => $value)  {
			  if(in_array($field,$arrfields)) {
			    $arrsave[$field] = $value;
			    if($field == "startDate" || $field == "endDate")  {
				  if($value != "")  {
				    list($g,$m,$a) = explode("/",$value);
				    $value = "$a-$m-$g";
				  } else {
				     $value = "0000-00-00";  
				  }
				  $qry_fields .= ",$field='$value'";
				} elseif($field != "idbanner") {
				    if($field == "idclient")
				      $qry_fields = "$field='$value'";
					else
				      $qry_fields .= ",$field='$value'";    
				  }
			  }  
			}
############################## controllo impressions ############################
			if(!array_key_exists("imptotal",$post))
			  $qry_fields .= ",imptotal='0'";
			if(!array_key_exists("startDate",$post))
			  $qry_fields .= ",startDate='0000-00-00'";
			if(!array_key_exists("endDate",$post))
			  $qry_fields .= ",endDate='0000-00-00'";
#################################################################################
		 $qry = "UPDATE banner SET $qry_fields $my_swf WHERE idbanner='".$this->fields["idbanner"]."';";
		 //die($qry);
		 $rs = $conn->Execute($qry);
		 if($rs)  {
/////////////////////////copio swf o immagine ////////////////////////////////////
			         $id = $this->fields["idbanner"];
			         $connect = ftp_connect($ftp_host);
					 $login = ftp_login($connect, $ftp_username, $ftp_pwd); 
			         $connect = ftp_connect($ftp_host);
					 $login = ftp_login($connect, $ftp_username, $ftp_pwd); 
			         if(!is_dir($path_image_Banner."/".$id))
					   ftp_mkdir($connect, $path_image_Banner_ftp.$id);
					 ftp_site($connect, "CHMOD 0777 ".$path_image_Banner_ftp.$id);
					 if(file_exists($path_tmp.$image["name"]) && $image["name"] != "") {
					     if(copy($path_tmp.$image["name"],$path_image_Banner.$id."/".$image["name"]))
					       @unlink($path_tmp.$image["name"]);
					       if($this->fields["imageurl"] != $image["name"])
					         @unlink($path_image_Banner."/".$id."/".$this->fields["imageurl"]);
					   }
//////////////////////////////////////////////////////////////////////////////////
         			$error = "Banner aggiornato con successo!";
         			ftp_site($connect, "CHMOD 0755 ".$path_image_Banner_ftp.$id);
					$rs->Close();
	        } else {
	             $error = "Aggiornamento errato.<br>Ripetere l'operazione.";
			}
		return $error;			  		   			
		  }
			
		  function delete()  {
	    	global $conn,$admin,$path_image_Banner, $path_image_Banner_ftp, $path_tmp, $max_size_image, $ftp_host,$ftp_username, $ftp_pwd, $_CONFIG;	    	
			    $qry = "DELETE FROM banner WHERE idbanner='".$this->fields["idbanner"]."';";
				$rs = $conn->Execute($qry);
				if($rs)  {
				   $error = "Il Banner &egrave; stato eliminato con successo!";
				     // cancello la directory delle immagini in ftp
			         $connect = ftp_connect($ftp_host);
					 $login = ftp_login($connect, $ftp_username, $ftp_pwd); 
				  	 $files = ftp_nlist($connect, $path_image_Banner_ftp.$this->fields["idbanner"]);
				  	 if(is_array($files) && count($files) > 0)  {
					   foreach($files as $chiave => $nome)  { 
					     @ftp_delete($connect, $nome);
					   }
					 }  
					   ftp_rmdir($connect, $path_image_Banner_ftp.$this->fields["idbanner"]);
					   ftp_quit($connect);
				} else
				   $error = "Errore nell'operazione.";
				 return $error;    	    		     			
		  }

		  function up()  {
			global $conn;
			   $ordineup = $this->fields["ordine"]-1;
		       $qryup = "UPDATE banner SET ordine=ordine+1 WHERE ordine='$ordineup'  AND posizione='".$this->fields["posizione"]."';";
		       $rs = $conn->Execute($qryup);
		       if ($rs) {
		        $qry = "UPDATE banner SET ordine=ordine-1 WHERE ordine='".$this->fields["ordine"]."' AND idbanner='".$this->fields["idbanner"]."' AND posizione='".$this->fields["posizione"]."';";
		        $rs = $conn->Execute($qry);
		        if($rs) {
		          $error = "0";
		        }  else  {
		          $error = "Errore nell'operazione.";
		        }
		       }  else
		         $error = "Errore nell'operazione.";
		         $rs->Close();
		       return $error;   
		  }
		  
		  function down()  {
			    global $conn;
			   $ordinedown = $this->fields["ordine"] + 1;
		       $qrydown = "UPDATE banner SET ordine=ordine-1 WHERE ordine='$ordineup'  AND posizione='".$this->fields["posizione"]."';";
		       $rs = $conn->Execute($qrydown);
		       if ($rs) {
		        $qry = "UPDATE banner SET ordine=ordine+1 WHERE ordine='".$this->fields["ordine"]."' AND idbanner='".$this->fields["idbanner"]."' AND posizione='".$this->fields["posizione"]."';";
		        $rs = $conn->Execute($qry);
		        if($rs) {
		          $error = "0";
		        }  else  {
		          $error = "Errore nell'operazione.";
		        }
		       }  else
		         $error = "Errore nell'operazione.";
		         $rs->Close();
		       return $error;    
		  }
		  
		  function disactive()  {
		    global $conn;
			$qry = "UPDATE banner SET attivo='0' WHERE idbanner='".$this->fields["idbanner"]."';";  
		    $rs = $conn->Execute($qry);
		        if($rs) {
		          $error = "0";
		        }  else  {
		          $error = "Errore nell'operazione.";
		        }
		         $rs->Close();
		       return $error;        
		  }
  
		  function active()  {
		    global $conn;
			$qry = "UPDATE banner SET attivo='1' WHERE idbanner='".$this->fields["idbanner"]."';";  
		    $rs = $conn->Execute($qry);
		        if($rs) {
		          $error = "0";
		        }  else  {
		          $error = "Errore nell'operazione.";
		        }
		         $rs->Close();
		       return $error;            
		   }
	   				
		   function checkSize($posizione)  {
			 global $_CONFIG;
			 switch($posizione)  {
			   case "alto":
			     $width = $_CONFIG["alto_width"];
				 $height = $_CONFIG["alto_height"]; 
			   break;  

			   case "destra":
			     $width = $_CONFIG["destra_width"];
				 $height = $_CONFIG["destra_height"]; 
			   break;  

			   case "basso":
			     $width = $_CONFIG["basso_width"];
				 $height = $_CONFIG["basso_height"]; 
			   break;  

			   case "sinistra":
			     $width = $_CONFIG["sinistra_width"];
				 $height = $_CONFIG["sinistra_height"]; 
			   break;  
			 }
			 define('WIDTH',$width);
			 define('HEIGHT',$height); 
		   }  
	  function search($search)  {
	    global $conn,$admin;
	    if(strlen($search) <= 2)  {
		  $error = printError("Hai inserito una parola non significativa. Riprova con un'altra.");
		  return $error;
		}
		$qry = "SELECT banner.idbanner FROM banner INNER JOIN banner_client ON banner.idclient=banner_client.idclient WHERE banner_client.nome LIKE '%$search%' OR banner.posizione LIKE '%$search%' ORDER BY banner.posizione,banner_client.nome ASC";
		$rs = $conn->Execute($qry);
		if($rs) {
			if($rs->RecordCount() > 0)  {
			  	 $i = $min + 1;
                 $content = "<table class=\"content\" width=\"100%\" align=\"center\" cellpadding=\"3\" cellspacing=\"0\" border=1>\n"
                 ."<tr>
					<td colspan=8>Sono stati trovati <b>".$rs->RecordCount()."</b> banner.</td>
				 	</tr>
				 <tr>
				   <td class=\"tbtit\" align=\"center\" width=\"10%\"><b>Numero</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"10%\"><b>Posizione</b></td>
				   <td class=\"tbtit\" align=\"\" width=\"10%\"><b>Ordine</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"20%\"><b>Cliente</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"20%\"><b>Scadenza</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"10%\"><b># Click</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"10%\"><b>Note</b></td>
				   <td class=\"tbtit\" align=\"center\" width=\"30%\"><b>Azioni</b></td>
				 </tr>";
               while (!$rs->EOF)  {
			    $newBanner = new banner($rs->Fields("idbanner"));
				$idbanner = $newBanner->fields['idbanner'];
				$client = new bannerClient($newBanner->fields["idclient"]);
			   	if($newBanner->fields['attivo'] == "1")
				    $semaforo = "<a href=\"banner.php?op=disactive&idbanner=$idbanner\"><img src=\"imgs/ico_green.jpg\" border=0 alt=Disattiva></a>";
				   else
				    $semaforo = "<a href=\"banner.php?op=active&idbanner=$idbanner\"><img src=\"imgs/ico_red.jpg\" border=0 alt=Attiva></a>";
				  $azioni = "<a href=\"banner.php?op=mod&idbanner=$idbanner\"><img src=\"imgs/ico_edit.gif\" alt=\"modifica\" width=16 height=16 title=\"modifica\" border=\"0\"></a>&nbsp;&nbsp;
                  <a href=\"banner.php?op=delete&idbanner=$idbanner\" onclick='return confirm(\"Sei sicuro di voler eliminare questo Banner? \")'><img src=\"imgs/ico_delete.gif\" width=16 height=16 alt=\"cancella\" title=\"cancella\" border=\"0\"></a>&nbsp;&nbsp;".$semaforo;
				if(!is_null($newBanner->fields["endDate"]))  {
				  // scadenza a data
				  $scadenza = $newBanner->fields["endDate"];
				} else {
				   $scadenza = $newBanner->fields["imptotal"]." impressions";
				} 
                 $content .= "<tr>
				  				<td class=\"tbtit\" align=\"center\" width=\"10%\"><b>$i</b></td>
				 				<td class=tdelenco align=center>&nbsp;".$newBanner->fields['posizione']."</td>
								<td class=tdelenco align=center>".$newBanner->fields['ordine']."</td>
								<td class=tdelenco align=center>".$client->nome."</td>
								<td class=tdelenco align=center>$scadenza</td>
								<td class=tdelenco align=center>&nbsp;".$newBanner->fields['clicks']."</td>
								<td class=tdelenco align=center>&nbsp;".$newBanner->fields['note']."</td>
								<td align=\"center\" valign=\"middle\" class=tdelenco>
								 $azioni";
                 $content .= "</td>
				 </tr>\n";
				 $rs->MoveNext();
				 $i++;
              }
			     $content .= "</table>";  
				 $rs->Close();
			} else {
			  $content = printError("La ricerca non ha prodotto nessun risultato.");		  
			}
		  $rs->Close();	
		} else {
			  $content = printError("La ricerca non ha prodotto nessun risultato.");		  
			}	
		return $content; 
	  }
	  
	  function getBennerList($pagina,$posizione,$ordine)  {
	    global $conn,$lang;
		$qry = "SELECT idbanner FROM banner WHERE (sezione='$pagina' OR sezione='tutte') AND posizione='$posizione' AND ordine='$ordine' AND attivo='1' AND (endDate > '".date("Y-m-d")."' OR impmade <= imptotal) AND lang='$lang';";
		$rs = $conn->Execute($qry);
		if($rs)  {
		  $banner = Array();
		  while(!$rs->EOF)  {
		    $banner[$rs->Fields("idbanner")] = new banner($rs->Fields("idbanner"));
			$rs->MoveNext();  
		  }
		  $rs->Close();
		}
		return $banner;  
	  }
	  
	  function getCookieBanner($pagina,$posizione,$ordine)  {
######################### leggo il cookie e restituisco il prossimo banner ########
	    global $conn,$_COOKIE;
		$idbanner = $_COOKIE["banner".$pagina.$posizione.$ordine];
		$banner = banner::getBennerList($pagina,$posizione,$ordine);
		if(is_array($banner))  {
		  reset($banner);
		  if($idbanner != "" && array_key_exists($idbanner,$banner))  {
		      $key = 0;
			  while($key != $idbanner)  {
			    list($key,$value) = each($banner);
			  }
		  }
		  if(current($banner))  {
			  if($nextBanner = current($banner)) {
			    return $nextBanner;
			  } else {
			    reset($banner);
				$nextBanner = current($banner);
				return $nextBanner;  
			  }
		  } else {
			    reset($banner);
				$nextBanner = current($banner);
				return $nextBanner;  		      
		   }   
		}  
	  }

	  function setCookieBanner()  {
#################### scrivo il cookie del banner relativo #########################
	    global $conn,$_CONFIG;
		setcookie("banner".$this->fields['sezione'].$this->fields['posizione'].$this->fields['ordine'],$this->fields['idbanner'],time() + $_CONFIG['bannerexpire'],"/",".bsvillage.com");  
	  }
	  
	  function getIt()  {
	    global $_CONFIG,$conn,$posizione;
	    if($this->fields['imageurl'] != "")  {
		    banner::checkSize($posizione);
		    $tipo = substr($this->fields['imageurl'], -3);
		    switch($tipo)  {
			  case "swf":
			    $content = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="'.$_CONFIG[$this->fields['posizione'].'_width'].'" height="'.$_CONFIG[$this->fields['posizione'].'_height'].'">
	                <param name="movie" value="http://'.$_CONFIG['domain'].'/gestione/imgs_Banner/'.$this->fields['idbanner'].'/'.$this->fields['imageurl'].'">
	                <param name="quality" value="high">
	                <embed src="/gestione/imgs_Banner/'.$this->fields['idbanner'].'/'.$this->fields['imageurl'].'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'.$_CONFIG[$this->fields['posizione'].'_width'].'" height="'.$_CONFIG[$this->fields['posizione'].'_height'].'"></embed>
	              </object>';
			  break;
			  
			  default:
			    $content = '<a href="/getBanner.php?idbanner='.$this->fields['idbanner'].'" target=_BLANK><img src="/gestione/imgs_Banner/'.$this->fields['idbanner'].'/'.$this->fields['imageurl'].'" border=0 width="'.$_CONFIG[$this->fields['posizione'].'_width'].'" alt="'.$this->fields['alttext'].'"></a>';
			  break;
			}
			$this->setCookieBanner(); 
			if($this->fields['imptotal'] != "0")  {
			  $qry = "UPDATE banner SET impmade = impmade + 1 WHERE idbanner='".$this->fields['idbanner']."';";
			  $rs = $conn->Execute($qry);
			  if($rs)
			    $rs->Close();
			}
		} else
		   $content = NULL;
		return $content;
	  }
	  
	  function clickBanner()  {
	    global $conn;
			  $qry = "UPDATE banner SET clicks = clicks + 1 WHERE idbanner='".$this->fields['idbanner']."';";
			  $rs = $conn->Execute($qry);
			  if($rs)
			    $rs->Close();	  
	  }
	  
	  function getPromozioni($cid) {
	  	 global $conn;
	  	$elencoB = "0";
		$elencoV = "0";
		$elencoN = "0";
		switch($cid)  {
			case 2:
				$titolo = "Piscine";
				break;

			case 3:
		  $titolo = "Giardino";
		  break;

			case 267:
		  $titolo = "Casa";
		  break;

			case 4:
		  $titolo = "Sport";
		  break;
		}
		$list = category::getChild($cid,$cid);
	    $qry = "SELECT a.idarticolo as idarticolo,a.titolo1 as titolo1 FROM 
	    articoli_new a INNER JOIN articoli_promo ap ON a.idarticolo=ap.idarticolo WHERE ap.idbanner=".$this->fields['idbanner']." ORDER BY titolo1;";
		$rs = $conn->Execute($qry);
		$result = '<table class="content">';
		if($rs->RecordCount()>0)  {
			while(!$rs->EOF)  {
				$elencoB .= ','.$rs->Fields("idarticolo");
				$result .= '<tr>
	      				<td width="500">'.htmlentities($rs->Fields("titolo1")).'</td>
	      				<td align="center"><img src="imgs/ico_delete.gif" alt="Togli dai Banner" onClick="if(confirm(\'Sei sicuro di voler togliere questo articolo dalla Promo? Procedere?\')) ajax_del_promozioni('.$rs->Fields("idarticolo").','.$this->fields['idbanner'].')"></td>
		  			  </tr>';
		  $rs->MoveNext();
			}
		}
		$result .= '<tr>
	  				<td colspan=2>SELEZIONA la Categoria per la PROMO:';
		$sql = "SELECT titolo,cid FROM categorie WHERE cid IN (SELECT DISTINCT cid FROM articoli_new WHERE giardino=0 AND attivo='y')
		OR cid IN (SELECT DISTINCT cid FROM categorie_correlate) 
		ORDER BY titolo ASC;";
		$rs_menu = $conn->Execute($sql);
		$result .= $rs_menu->GetMenu("cid","","0:SELEZIONA...",false,0,"id='cid_banner' style='width:500px'");
		$rs_menu->Close();
		$result .= '</td></tr>';
		$result .= '<tr>
	  				<td colspan=2>OPPURE Aggiungi articolo per la PROMO:';
		$sql = "SELECT titolo1,idarticolo FROM articoli_new WHERE idarticolo NOT IN ($elencoB) AND cid IN ($list) ORDER BY titolo1 ASC;";
		$rs_menu = $conn->Execute($sql);
		$result .= $rs_menu->GetMenu("idarticolo","",false,false,0,"id='idarticolo_banner' style='width:500px'");
		$rs_menu->Close();
		$result .= '&nbsp;&nbsp;<input type="button" value="AGGIUNGI" onClick="ajax_add_promozioni('.$this->fields['idbanner'].');">
		&nbsp;&nbsp;<input type="button" value="CANCELLA TUTTO" onClick="ajax_svuota_promozioni('.$this->fields['idbanner'].');"></td>
	  			  </tr>';
		$result .= '</table>';
		return $result;
	  }
	  
	  function addArticoloPromo($idbanner,$idarticolo,$cid) {
	  	 global $conn;
	  	 if($cid!="") {
	  	 	$qry = "SELECT idarticolo FROM articoli_new WHERE cid=$cid AND attivo='y' UNION DISTINCT 
	  	 	SELECT idarticolo FROM categorie_correlate WHERE cid=$cid;";
	  	 	$rs = $conn->Execute($qry);
	  	 	if($rs->RecordCount()>0) {
	  	 		while(!$rs->EOF) {
	  	 			$qry = "INSERT INTO articoli_promo VALUES($idbanner,".$rs->Fields("idarticolo").");";
	  	    		$conn->Execute($qry);
	  	 			$rs->MoveNext();
	  	 		}
	  	 		$rs->Close();
	  	 	}
	  	 } else {
	  	    $qry = "INSERT INTO articoli_promo VALUES($idbanner,$idarticolo);";
	  	    $conn->Execute($qry);
	  	 }
	  }
	  
	function delArticoloPromo($idbanner,$idarticolo) {
	  	 global $conn;
	  	 $qry = "DELETE FROM  articoli_promo WHERE idbanner=$idbanner AND idarticolo=$idarticolo;";
	  	 $conn->Execute($qry);
	  }
	  
	function svuotaPromo($idbanner) {
	  	 global $conn;
	  	 $qry = "DELETE FROM articoli_promo WHERE idbanner=$idbanner;";
	  	 $conn->Execute($qry);
	  }
	  
	function showPromo($url) {
		global $conn;
		$qry = "SELECT a.idarticolo as idarticolo,
		(SELECT idbanner FROM banner WHERE alttext='".fromUrlToTit($url)."' AND attivo=1 AND startDate <= NOW() 
		AND endDate >= NOW()) as idbanner FROM articoli_promo ap INNER JOIN articoli_new a 
		ON ap.idarticolo=a.idarticolo WHERE idbanner = 
		(SELECT idbanner FROM banner WHERE alttext='".fromUrlToTit($url)."' AND attivo=1 AND startDate <= NOW() 
		AND endDate >= NOW()) ORDER BY a.prezzo2;";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0) {
			$i = 1;
			$c = 1;
			$banner = new banner($rs->Fields("idbanner"));
			$result = '<div class="plain"><h1 class=tit02 style="text-transform: uppercase;margin-left:20px;">PROMOZIONI BSVILLAGE</h1>';
			if($banner->fields['imageurl']!="") $result .= '<div style="padding:10px;">
			<p style="margin-bottom:20px;"><img src="/gestione/imgs_Banner/'.$banner->fields['idbanner'].'/'.$banner->fields['imageurl'].'" /></p>
			</div>';
			$result .= '<div class="content-articoli" style="margin-left:10px;">';
			while(!$rs->EOF) {
				$folder2 = "piscine";
			 $art = new articoli($rs->Fields("idarticolo"));
		 	 switch($art->disp)  {
				case "-1":
					$strdisp = '<br>  <span style="color:red;"><b>Articolo al momento esaurito!</b></span>';
					break;
	
				case "0":
					$strdisp = '<br>  <span style="color:red;"><b>Disponibilit&agrave; dell\'articolo da verificare.</b></span>';
					break;
	
				case "1":
					$strdisp = '';
					break;
			    }
		 	$permalink = strPermalink($art->hidden);
		 	if($art->codice!="")
		 	$codice = '<br><b>COD. '.$art->codice.'</b>';
		 	else
		 	$codice = "";
		 	if($art->import==1)
		 	$folder = "/immagini-piscine";
		 	else
		 	$folder = "/gestione/imgs_prodotti/".$art->idarticolo;
		 	if($art->image!="")
		 	$image_tmb = "<a href=\"/$permalink/".$art->idarticolo."\" title=\"".$art->titolo1."\"><img width=80 src=\"$folder/".str_replace(" ","_",$art->image)."\" border=0 alt=\"".$art->titolo1."\"></a>";
		 	else
		 	$image_tmb = "&nbsp;";
		 	list($listino,$scontato,$spedizione) = articoli::getPrezzo($art->idarticolo,$art->cid,$art->prezzo1,$art->prezzo2,10,$art->fornitore);
		 	if($art->prezzo2 != "0" && $art->promozione == "y") {
			  $prezzo = '<span class="prezzo_elenco">'.number_format($scontato,2,",",".").' &euro;</span>';
			  $prezzosc = $prezzo2.': '.number_format($scontato,2,",",".").' &euro;';
		 	}	else  {
			  $prezzo = '<span class="prezzo_elenco">'.number_format($listino,2,",",".").' &euro;</span>';
			  $prezzosc = "&nbsp;";
		 	}
		 	$titolo = '<a class=plain href="/'.$permalink.'/'.$art->idarticolo.'" title="'.$art->titolo1.'">'.$art->titolo1.'</a>';
		 	if($art->vetrinacat == 1) {
		 		if(!$vetrina) {
		 			$vetrina = true;
		 			$content .= '<div class="tit02" style="width:100%">In vetrina</div>';
		 		}
		 		$style = 'style="background-color:#ffeeda;border-bottom:1px solid #FFFFFF"';
		 	} elseif($i % 2 == 1) {
			  //$content .= "<tr bgcolor=#FFFFFF>";
			  $style = 'style="background-color:#FFFFFF"';
		 	} else {
		 		//$content .= "<tr bgcolor=#F6F7F4>";
		 		$style = 'style="background-color:#F6F7F4"';
		 	}
		 	$arr_news = explode(" ",strip_tags($art->desc));
		 	if(count($arr_news)>10) {
		 		$strillo = '';
		 		for($y=0;$y<=10;$y++) {
		 			if($y>0) $strillo.=' ';
		 			$strillo .= $arr_news[$y];
		 		}
		 		$strillo .= "...";
		 	} else
		 	$strillo = $art->desc;
			
			list($listino,$scontato,$spedizionev) = articoli::getPrezzo($art->idarticolo,$art->cid,$art->prezzo1,$art->prezzo2,($art->spedizione > 0 && $art->spedizione != 9999 ? $art->spedizione : 10),$art->fornitore);		
			$speseSpedizione = '';
			$speseSpedizioneTab = '';
			 if ($art->spedizione==0 || $spedizionev == 0){
				 $speseSpedizione = '<div class="icoSpedOmaggio"></div>';
				 $speseSpedizioneTab = '<img src="http://www.bsvillage.com/images/icoSpedOmaggio.png" style="margin-left:10px; float:left" />';
			 }
			 
			 $prodNew = '';
			 if ($art->novita=="y"){
				 //$prodNew = '<div class="icoProdNew"></div>';
			 }
			 
			 if (!isset($_REQUEST['tab'])) {
					$result .= '<div class="box-image-articoli" '/*.$style*/.'>'.$image_tmb.' '.$codice.$prodNew.'</div>
								 <div class="box-titolo-articoli" '.$style.'>
								 <a class=plain href="/'.$permalink.'/'.$art->idarticolo.'">'.htmlentities($art->titolo1).'</a><br>
					'.htmlentities($strillo).'<br>
					<a href="/'.$permalink.'/'.$art->idarticolo.'" title="'.$art->titolo1.'" class="dettProd">Caratteristiche &gt;'./*'<img style="margin-top:10px" src="/images/apriScheda.jpg" border=0>'.*/'</a>'.
					'<a href="/'.$permalink.'/'.$art->idarticolo.'#form" title="'.$art->titolo1.'" class="richiediInfoProd">Richiedi info</a>
					'.$speseSpedizione.'
					'.$strdisp.'
								 </div>
								 <div class="box-prezzo-articoli" '.$style.'>'.$prezzo.'<br>
					<a href="javascript:;" onClick="addArticolo(\''.$art->idarticolo.'\')"><img src="/images/compralo.gif" border=0></a><br><p class="btnFB"><fb:like layout="button_count" href="http://www.bsvillage.com/'.$permalink.'/'.$art->idarticolo.'"></fb:like><p></div>';  	
			 } else {
				$bgcolor = ($i%2==0)?"style=\"background:#F6F7F4;":"style=\"";
				$result .= '<table width="660" border="0" cellspacing="0" cellpadding="0" style="margin-bottom:5px">
					  			<tr>
									<td width="80">'.$image_tmb.' '.$codice.'</td>
									<td width="10"></td>
									<td width="420" valign="top" '.$bgcolor.'font-size:11px;">
										<a class=plain href="/'.$permalink.'/'.$art->idarticolo.'" style="color:#7584A1;font-weight:bold;text-decoration: none;">'.htmlentities($art->titolo1).'</a>
										<br>
										'.($art->titolo2!="" ? htmlentities($art->titolo2).'<br>' : '').'
										'.htmlentities($strillo).'<br>
										<a href="/'.$permalink.'/'.$art->idarticolo.'" title="'.$art->titolo1.'" class="dettProd">Caratteristiche &gt;'./*'<img style="margin-top:10px" src="/images/apriScheda.jpg" border=0>'.*/'</a>'.
										'<a href="/'.$permalink.'/'.$art->idarticolo.'#form" title="'.$art->titolo1.'" class="richiediInfoProd">Richiedi info</a>
										'.$speseSpedizioneTab.'
										'.$strdisp.'
									</td>
									<td width="150" '.$bgcolor.'color:#666666;font-size: 15px;font-weight: bold;">
										'.$prezzo.'<br>
							 			<a href="javascript:;" onClick="addArticolo(\''.$art->idarticolo.'\')"><img src="/images/compralo.gif" border=0></a>
									</td>
					  			</tr>
							 </table>';
			 }
		 	$i++;
				$rs->MoveNext();
			}
			$result .= '</div>
			</div>';
			$rs->Close();
		}
		return $result;
	}
	
	function showPromozioni() {
		global $conn;
		$qry = "SELECT idbanner,alttext,imageurl FROM banner WHERE attivo=1 AND startDate <= NOW() 
		AND endDate >= NOW() AND alttext!='' ORDER BY ordine;;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount()>0) {
			$result = '<div class="plain"><h1 class=tit02 style="text-transform: uppercase;margin-left:20px;">PROMOZIONI BSVILLAGE</h1>';
			while(!$rs->EOF) {
				if($rs->fields('imageurl')!="") $result .= '<div style="padding:10px;">
				<p style="margin-bottom:20px;">
				<a href="/promozioni/'.strPermalink($rs->Fields("alttext")).'/"><img src="/gestione/imgs_Banner/'.$rs->fields('idbanner').'/'.$rs->fields('imageurl').'" border="0" /></a></p>
				</div>';
				$rs->MoveNext();
			}
			$result .= '</div>';
			$rs->Close();
		}
		return $result;
	}
} 

	class bannerConfig {
	  var $config;
	  
	  function bannerConfig()  {
	    global $conn;
	    $this->config = array();
		$qry = "SELECT * FROM banner_config;";
		$rs = $conn->Execute($qry);
		if($rs->RecordCount() > 0) {
		  $fields = $rs->FieldCount();
		  for($i=0;$i<$fields;$i++)  {
		    $field = $rs->FetchField($i);
			$this->config[$field->name] = $rs->Fields($field->name);
		  }
		} else 
		   $this->config = NULL; 
	  }
	  
	  function update($post)  {
	    global $conn;
		foreach($this->config as $field => $value) {
		  $post[$field] = str_replace(",",".",$post[$field]);
		  $this->config[$field] = $post[$field];
		  if($field == "alto_width")
		    $qry_fields = "$field='".$this->config[$field]."'";
		  else
		    $qry_fields .= ",$field='".$this->config[$field]."'";  
		}
		$qry = "UPDATE banner_config SET $qry_fields;";
		//die($qry);
		$rs = $conn->Execute($qry);
		if($rs)  {
		  $error = "Parametri di configurazione aggiornati con successo!";
		  $rs->Close();
		} else
		  $error = "Errore nell'aggiornamento.";
		return $error;  	      
	  }
}
?>